<?php
function goUrl($url,$param =[], $func = null)
{
    /** @var callable $func */
    go(function () use ($url,$param, $func) {
        $parsedUrl = parse_url($url);
        if (!$parsedUrl || !isset($parsedUrl['host'])) {
            $func && $func('{"code":-1,"msg":"invalid url"}');
            return;
        }
        $host = $parsedUrl['host'] ?? ''; // 主机名
        $port = $parsedUrl['port'] ?? (strtolower($parsedUrl['scheme'] ?? '') === 'https' ? 443 : 80);
        $path = $parsedUrl['path'] ?? '/'; // 路径
        $query = $parsedUrl['query'] ?? ''; // 查询参数
        $fullPath = $path . ($query ? '?' . $query : '');
        $client = new Swoole\Coroutine\Http\Client($host, $port, $port === 443);
        $client->set([
            'timeout' => 5.0,
        ]);
        $client->setHeaders([
            'Host' => $host,
            'User-Agent' => 'Swoole HTTP Client',
        ]);
        if($param){
            $client->post($fullPath,$param);
        }else{
            $client->get($fullPath);
        }

        $response = $client->body ?: '{"code":-1,"msg":"empty response"}';

        $statusCode = $client->statusCode;
        // 可选：记录响应日志
        if ($statusCode != 200) {
            echo (var_export(compact('url', 'response'), true));
        }
        $client->close();
        if ($func) {
            $func($response);
        }

    });
}

function getParams($params = []){
    $list =  [
        '#date#' => function($params,$column){
            return date('Y-m-d');
        },
        '#yestoday#' => function($params,$column){
            return date('Y-m-d',strtotime("-1 day"));
        },
    ];
    $result = [];
    foreach ($params as $key){
        $calc = $list[$key] ?? null;
        if(!$calc) continue;
        $column = trim($key,'#');
        $result[$column] = $calc($params,$column);
    }
    return $result;

}

function singleDb($gameDb,$table){
    $single_db = str_replace('game_','admin_s',$gameDb);
    return $single_db.'.'.$table;
}

function getGameDb($platform,$plat_server){
    return GAME_NAME."_".$platform."_game_".$plat_server;
}

function getUrl($platform,$plat_server){
    return 'http://127.0.0.1';
}

function NewPHP2Erlang($url,$platform,$plat_server,$type, $data,$func=null,$error=null)
{
    /** @var callable $func */
    /** @var callable $error */
    $field = [

    ];
    $listData = array_values(array_intersect_key($data,array_flip($field)));
    $jsonData = empty($listData) ? "{}" : "{" . implode(",", $listData) . "}";
    echo $jsonData;

    switch ($type) {
        case BACKGROUND_RECHARGE:
            $signKey = SERVER_PAY_KEY;
            break;
        default:
            $signKey = SERVER_BACKGROUND_KEY;
            break;
    }

    //请求参数
    $nowTime = time();
    $paramArr = array("platform" => $platform, "server_num" => $plat_server, "do" => $type, "data" => $jsonData, "time" => $nowTime);
    //增加token参数
    $paramArr["token"] = strtolower(md5(join("", $paramArr) . $signKey));

    goUrl($url.'?'.http_build_query($paramArr),[],function ($response) use ($url,$paramArr,$func,$error){

        /** @var $error $func */
        echo ("请求url" . $url  . "/background" . "请求参数" . json_encode($paramArr, true) . "返回结果:" . $response);
        $result = json_decode($response, true);
        if ($result && $result["code"] == BACKGROUND_SUCCESS) {
            $func($result);
        }else{
            $error($result);
        }
    });

}